package com.hy.utils.face;

import com.alibaba.fastjson.JSONObject;
import com.hy.utils.GsonUtils;
import org.json.JSONArray;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@Component
public class BaiduAIFace {

    private static String token = GetToken.getAuth();

    /**
     * 人脸检测
     * @return
     */
    public Map facefaceDetect(Setingmodel facaddseting){
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/detect";
        Map<String, Object> map=new HashMap<>();
        try {
            map.put("image", facaddseting.getImgpath());
            map.put("liveness_control", facaddseting.getLiveness_Control());
            map.put("image_type", facaddseting.getImage_Type());
            map.put("quality_control", facaddseting.getQuality_Control());
            String param = GsonUtils.toJson(map);
            String result = HttpUtil.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;
        } catch (Exception e) {
            System.out.println("失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸注册
     */
    public  Map faceRegistration(Setingmodel facaddseting) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/add";
        Map resultmap = faceAddAndUpdate(facaddseting, url);
        return resultmap;
    }

    /**
     * 人脸更新
     * @param facaddseting 参数设置
     * @return 返回信息map
     * @throws IOException
     */
    public  Map faceUpdate(Setingmodel facaddseting) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/user/update";
        Map resultmap = faceAddAndUpdate(facaddseting, url);
        return resultmap;

    }

    /**
     * 插入人脸
     * @param facaddseting
     * @param url
     * @return
     * @throws IOException
     */
    private Map faceAddAndUpdate(Setingmodel facaddseting, String url) throws IOException {
        //图片base64格式 已在前端转换
        //byte[] bytes = Files.readAllBytes(Paths.get(facaddseting.getImgpath()));
        //String imagebase64 = Base64Util.encode(bytes);
        Map<String, Object> map=new HashMap<>();
        try {
            map.put("image", facaddseting.getImgpath());
            map.put("group_id", facaddseting.getGroupID());
            map.put("user_id", facaddseting.getUserID());
            map.put("liveness_control", facaddseting.getLiveness_Control());
            map.put("image_type", facaddseting.getImage_Type());
            map.put("quality_control", facaddseting.getQuality_Control());
            String param = GsonUtils.toJson(map);
            String result = HttpUtil.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;
        } catch (Exception e) {
            System.out.println("失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询这个人的面部信息
     * @param setingmodel
     * @return map
     */
    public Map findPersonFaceList(Setingmodel setingmodel){
        String url="https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/getlist";
        Map<String, Object> map=new HashMap<>();
        if(!map.isEmpty()){
            map.clear();
        }
        map.put("group_id", setingmodel.getGroupID());
        map.put("user_id", setingmodel.getUserID());
        String param = GsonUtils.toJson(map);

        try {
            String result = HttpUtil.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;
        } catch (Exception e) {
            System.out.println("查询失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 查询本组的面部信息
     * @param setingmodel
     * @return
     */
    public Map findGroupList(Setingmodel setingmodel) {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/faceset/group/getusers";
        Map<String, Object> map=new HashMap<>();
        map.put("group_id",setingmodel.getGroupID());
        //默认值0，起始序号
        map.put("start",0);
        //获取 30 张人脸
        map.put("length",30);
        String param = GsonUtils.toJson(map);
        try {
            String result = HttpUtil.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result, Map.class);
            return resultmap;

        } catch (Exception e) {
            System.out.println("未查询到人脸信息");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 删除 人脸
     * @param setingmodel
     * @return
     */
    public Map delPersonFace(Setingmodel setingmodel){
        String url="https://aip.baidubce.com/rest/2.0/face/v3/faceset/face/delete";
        Map map = findPersonFaceList(setingmodel);
        Object result = map.get("result");
        String s = GsonUtils.toJson(result);
        JSONObject jsonObject = JSONObject.parseObject(s);
        String face_token = jsonObject.getString("face_list");
        String substring = face_token.substring(2, face_token.length() - 2);
        String[] split = substring.split("\"");
        face_token=split[7];
        System.out.println(face_token);
        map.put("group_id", setingmodel.getGroupID());
        map.put("user_id", setingmodel.getUserID());
        map.put("face_token",face_token);
        String param = GsonUtils.toJson(map);
        try {
            String result2 = HttpUtil.post(url, token, "application/json", param);
            Map resultmap = GsonUtils.fromJson(result2, Map.class);
            return resultmap;
        } catch (Exception e) {
            System.out.println("删除失败");
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 人脸查找
     * @return
     */
    public Map faceSearch(Setingmodel setingmodel) throws IOException {
        String url = "https://aip.baidubce.com/rest/2.0/face/v3/search";
        //图片base64格式 已在前端转换
        //byte[] bytes = Files.readAllBytes(Paths.get(setingmodel.getImgpath()));
        //String imagebase64 = Base64Util.encode(bytes);
        try {
            Map<String, Object> map = new HashMap<>();
            map.put("image", setingmodel.getImgpath());
            map.put("liveness_control", setingmodel.getLiveness_Control());
            map.put("group_id_list", setingmodel.getGroupID());
            map.put("image_type", setingmodel.getImage_Type());
            map.put("quality_control", setingmodel.getQuality_Control());
            String param = GsonUtils.toJson(map);
            String result = HttpUtil.post(url, token, "application/json", param);
            Map<String,Object> rsmap = GsonUtils.fromJson(result, Map.class);
            //匹配成功
            if(rsmap.get("error_msg").toString().equals("SUCCESS")){
                String resultlist = rsmap.get("result").toString();
                System.out.println("result--->" + result);
                org.json.JSONObject rs = new org.json.JSONObject(result);
                System.out.println("外层-result:--->" + rs);
                Object rr = rs.get("result");
                org.json.JSONObject rst = new org.json.JSONObject(rr.toString());
                System.out.println("内层-result:--->" + rst);
                Object uls = rst.get("user_list");
                org.json.JSONArray user_list = new JSONArray(uls.toString());
                System.out.println("user_list:--->" + user_list);
                Object str = user_list.get(0);
                System.out.println("str:--->" + str);
                org.json.JSONObject sr = new org.json.JSONObject(str.toString());
                String score = sr.get("score").toString();
                System.out.println("score:--->" + score);
                String substring = resultlist.substring(1, resultlist.length() - 1);
                String regEx="[\n`~!@#$%^&*()+|{}':;'\\[\\].<>/?~！@#￥%……&*（）——+|{}【】‘；：”“’。， 、？]";
                String aa = "";
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(substring);//这里把想要替换的字符串传进来
                String newString = m.replaceAll(aa).trim();
                String[] split = newString.split(",");
                split[1]=split[1].substring(10, split[1].length());
                String face_token=split[0].substring(11,split[0].length());
                String group_id=split[1].substring(9,split[1].length());
                String user_id=split[2].substring(8,split[2].length());
                String user_info=split[3].substring(10,split[3].length());
                //有问题  9.879898 变成  9879898 截取两位 98 验证通过!!!
                //String score=split[4].substring(6,split[4].length());
                System.out.println("4---->"+split[4]);
                System.out.println("face_token:" + face_token);
                rsmap.put("face_token",face_token);
                rsmap.put("group_id",group_id);
                rsmap.put("user_id",user_id);
                rsmap.put("user_info",user_info);
                if (score.indexOf(".") != -1){
                    //例--->7.889887  77.0808   .分隔 需要用\\转义
                    score = score.split("\\.")[0];
                }else if(score.length() > 2){
                    //例--->100
                    score = score.substring(0,2);
                }
                //else--> 99 - 88 - 77 - 67
                rsmap.put("score",score);
                System.out.println("完整score-->:" + score);
                return rsmap;
            }else {
                System.out.println("未识别!");
                return rsmap;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

}
